package com.example.blog.controller;

import com.example.blog.constant.Constants;
import com.example.blog.model.Result;
import com.example.blog.model.UserInfo;
import com.example.blog.service.BlogService;
import com.example.blog.service.UserService;
import com.example.blog.utils.JwtUtils;
import com.example.blog.utils.SecurityUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public Result login(String userName, String password){
        //校验参数是否合法
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){
            return Result.fail("用户名或密码不能为空!");
        }
        //判断用户是否存在
        UserInfo userInfo = userService.selectByName(userName);
        if(userInfo == null){
            return Result.fail("用户名或密码错误!");
        }
        //判断密码是否正确
        if(!SecurityUtils.verify(password, userInfo.getPassword())) {
            return Result.fail("密码错误!");
        }

        // 密码正确，返回token
        Map<String, Object> claim = new HashMap<>();
        claim.put(Constants.TOKEN_ID, userInfo.getId());
        claim.put(Constants.TOKEN_USERNAME, userInfo.getUserName());
        String token = JwtUtils.genJwtToken(claim);
        log.info("UserController login 返回结果token{}", token);
        return Result.success(token);
    }

    /**
     * 获取当前登录用户信息
     */
    @RequestMapping("/getUserInfo")
    public Result getUserInfo(HttpServletRequest request){
        log.info("获取当前登录用户信息");
        //从head中获取token
        String jwtToken = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        //从token中获取id
        Integer id = JwtUtils.getIdByToken(jwtToken);
        //通过id获取用户信息
        UserInfo userInfo = userService.selectById(id);
        if(userInfo == null){
            return Result.fail("获取当前登录用户失败");
        }else {
            return Result.success(userInfo);
        }
    }

    /**
     * 在博客详情页，获取当前文章作者的用户信息
     * @param
     * @return
     */
    @RequestMapping("/getAuthorInfo")
    public Result getAuthorInfo(Integer blogId){
        log.info("getAuthorInfo 获取参数blogId: {}", blogId);
        //参数校验
        if(blogId == null || blogId <= 0){
            return Result.fail("博客id错误");
        }
        UserInfo userInfo = userService.getAuthorInfo(blogId);
        if(userInfo == null){
            return Result.fail("获取作者信息失败");
        }
        return Result.success(userInfo);
    }
}
